package vashion.azeroth.crm.service.impl;

import java.util.ArrayList;
import java.util.List;

import lombok.NonNull;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import vashion.azeroth.core.api.request.AddOrderRequest;
import vashion.azeroth.core.api.request.Detail;
import vashion.azeroth.core.api.request.Invoice;
import vashion.azeroth.core.api.request.Payment;
import vashion.azeroth.core.api.response.AddOrderResponse;
import vashion.azeroth.core.api.service.ApiOrderService;
import vashion.azeroth.core.manager.personal.tran.PersonalDisburseManager;
import vashion.azeroth.core.manager.personal.tran.PersonalRechargeOrderManager;
import vashion.azeroth.core.personal.tran.pojo.PersonalDisburse;
import vashion.azeroth.core.personal.tran.pojo.PersonalRechargeOrder;
import vashion.azeroth.core.personal.tran.pojo.PersonalSnapshot;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.item.ItemSkuService;
import vashion.azeroth.crm.constant.CrmUtil;
import vashion.azeroth.crm.constant.GenericCrmErrorEnum;
import vashion.azeroth.crm.constant.OrderParameterConstant;
import vashion.azeroth.crm.service.CrmWriteService;

public class CrmWriteServiceImpl implements CrmWriteService {

	private final static Logger log = LoggerFactory
			.getLogger(CrmWriteServiceImpl.class);

	@Autowired
	PersonalDisburseManager personalDisburseManager;

	@Autowired
	PersonalRechargeOrderManager personalRechargeOrderManager;

	@Autowired
	ApiOrderService apiOrderService;

	@Autowired
	ItemSkuService itemSkuService;

	@Override
	public ApiResult<String> syncOrderToErp(String orderNO, int orderType) {

		// ----------------根据订单类型判断-------------------------

		/**
		 * 消费订单为：1
		 * 
		 * 充值订单为：2
		 * 
		 * */

		if (orderType != 1 && orderType != 2) {

			return ApiResult.newErrorResult(
					GenericCrmErrorEnum.ORDER_TYPE_NOT_EXIST.getErrorCode(),
					GenericCrmErrorEnum.ORDER_TYPE_NOT_EXIST.getErrorMessage());
		}

		if (StringUtils.isEmpty(orderNO)) {

			return ApiResult.newErrorResult(
					GenericCrmErrorEnum.PARAMETER_ERROR.getErrorCode(),
					GenericCrmErrorEnum.PARAMETER_ERROR.getErrorMessage());
		}

		// ----------------查询订单信息-------------------------

		AddOrderRequest addOrderRequest = new AddOrderRequest();

		if (orderType == 1) {

			PersonalDisburse personalDisburse = personalDisburseManager
					.getByDisburseNo(orderNO);

			convertToOrderRequest(personalDisburse, addOrderRequest);

		}

		if (orderType == 2) {

			PersonalRechargeOrder personalRechargeOrder = personalRechargeOrderManager
					.getRechargeOrderByDisburseNo(orderNO);

			convertToOrderRequest(personalRechargeOrder, addOrderRequest);

		}

		// ----------------确认订单状态-------------------------

		/*
		 * do nothing
		 * 
		 * *
		 */

		// ----------------同步ERP-------------------------

		AddOrderResponse response = apiOrderService.addOrder(addOrderRequest);

		if (response.isSuccess()) {

			String orderId = response.getId();

			log.info("同步ERP成功：orderId=" + orderId);

		}

		return null;

	}

	private void convertToOrderRequest(Object obj,
			AddOrderRequest addOrderRequest) {

		PersonalDisburse personalDisburse;

		PersonalRechargeOrder personalRechargeOrder;

		if (obj instanceof PersonalDisburse) {

			personalDisburse = (PersonalDisburse) obj;

			List<PersonalSnapshot> snapshots = personalDisburse.getSnapshots();

			/**
			 * 店铺code
			 * */
			String shopCode = OrderParameterConstant.shopCode;

			addOrderRequest.setShopCode(shopCode);

			/**
			 * 物流公司code
			 * */
			String expressCode = OrderParameterConstant.expressCode;

			addOrderRequest.setExpressCode(expressCode);

			/**
			 * 仓库code
			 * */
			String warehouseCode = OrderParameterConstant.warehouseCode;

			addOrderRequest.setWarehouseCode(warehouseCode);

			/**
			 * 会员code
			 * */
			String vipCode = personalDisburse.getBuyerMemberName();

			addOrderRequest.setVipCode(vipCode);

			/**
			 * 拍单时间
			 * 
			 * 例：2015-03-17 15:03:45
			 * */
			String dealDatetime = CrmUtil.convertDateToString(personalDisburse
					.getTimeAdd());

			addOrderRequest.setDealDatetime(dealDatetime);

			/**
			 * 发票类型 1-普通发票；2-增值发票
			 * 
			 * */
			int invoiceType = OrderParameterConstant.invoiceType;

			addOrderRequest.setInvoiceType(invoiceType);

			/**
			 * details商品信息数组
			 * 
			 * */
			List<Detail> details = convertSnapshotToDetail(snapshots);

			addOrderRequest.setDetails(details);

			/**
			 * payments支付信息数组
			 * 
			 * */
			List<Payment> payments = convertToPayment(personalDisburse);

			addOrderRequest.setPayments(payments);

			/**
			 * invoices发票信息数组
			 * 
			 * */

			List<Invoice> invoices = convertToInvoice();

			addOrderRequest.setInvoices(invoices);

		}

		if (obj instanceof PersonalRechargeOrder) {

			personalRechargeOrder = (PersonalRechargeOrder) obj;

			/**
			 * 店铺code
			 * */
			String shopCode = OrderParameterConstant.shopCode;

			addOrderRequest.setShopCode(shopCode);

			/**
			 * 物流公司code
			 * */
			String expressCode = OrderParameterConstant.expressCode;

			addOrderRequest.setExpressCode(expressCode);

			/**
			 * 仓库code
			 * */
			String warehouseCode = OrderParameterConstant.warehouseCode;

			addOrderRequest.setWarehouseCode(warehouseCode);

			/**
			 * 会员code
			 * */
			String vipCode = personalRechargeOrder.getMemberName();

			addOrderRequest.setVipCode(vipCode);

			/**
			 * 拍单时间
			 * 
			 * 例：2015-03-17 15:03:45
			 * */
			String dealDatetime = CrmUtil
					.convertDateToString(personalRechargeOrder.getTimeAdd());

			addOrderRequest.setDealDatetime(dealDatetime);

			/**
			 * 发票类型 1-普通发票；2-增值发票
			 * 
			 * */
			int invoiceType = OrderParameterConstant.invoiceType;

			addOrderRequest.setInvoiceType(invoiceType);

			/**
			 * details商品信息数组
			 * 
			 * */
			List<Detail> details = new ArrayList<Detail>();

			addOrderRequest.setDetails(details);

			/**
			 * payments支付信息数组
			 * 
			 * */
			List<Payment> payments = new ArrayList<Payment>();

			Payment paymentObj = new Payment();

			/**
			 * 支付类型code
			 * 
			 * @TODO 不知道传啥
			 * */
			@NonNull
			String payTypeCode = "111111";

			paymentObj.setPayTypeCode(payTypeCode);

			/**
			 * 支付金额
			 * 
			 * */
			@NonNull
			Double payment = Double
					.valueOf(personalRechargeOrder.getAmount() / 100);

			paymentObj.setPayment(payment);

			payments.add(paymentObj);

			addOrderRequest.setPayments(payments);

			/**
			 * invoices发票信息数组
			 * 
			 * */

			List<Invoice> invoices = convertToInvoice();

			addOrderRequest.setInvoices(invoices);

		}

	}

	private List<Detail> convertSnapshotToDetail(
			List<PersonalSnapshot> snapshots) {

		List<Detail> details = new ArrayList<Detail>();

		if (snapshots == null) {

			return null;
		}

		for (PersonalSnapshot personalSnapshot : snapshots) {

			Detail detail = new Detail();

			/**
			 * 商品代码
			 * 
			 * */

			String itemCode = personalSnapshot.getItemId().toString();

			detail.setItemCode(itemCode);

			/**
			 * 规格代码
			 * 
			 * */

			String skuCode = personalSnapshot.getSkuId().toString();

			detail.setSkuCode(skuCode);

			/**
			 * 实际单价
			 * 
			 * */

			Double price = Double.valueOf(personalSnapshot.getPrice() / 100);

			detail.setPrice(price);

			/**
			 * 商品数量
			 * 
			 * */

			int qty = personalSnapshot.getQuantity();

			detail.setQty(qty);

			/**
			 * 是否退款
			 * 
			 * 0非退款 ，1--退款（退款中）；
			 * 
			 * */

			int refund;

			/**
			 * 备注
			 * 
			 * */

			String note;

			/**
			 * 子订单ID
			 * 
			 * */

			String oid;

			details.add(detail);

		}

		return details;

	}

	private List<Payment> convertToPayment(PersonalDisburse personalDisburse) {

		List<Payment> payments = new ArrayList<Payment>();

		Payment paymentObj = new Payment();

		/**
		 * 支付类型code
		 * 
		 * @TODO 不知道传什么
		 * */
		@NonNull
		String payTypeCode = "payTypeCodeTest";
		paymentObj.setPayTypeCode(payTypeCode);

		/**
		 * 支付金额
		 * 
		 * */
		@NonNull
		Double payment = Double.valueOf(personalDisburse.getTotalPrice() / 100);
		paymentObj.setPayment(payment);

		/**
		 * 支付交易号
		 * 
		 * */
		String payCode;

		/**
		 * 支付账户
		 * 
		 * */
		String account;

		payments.add(paymentObj);

		return payments;
	}

	private List<Invoice> convertToInvoice() {

		// #TODO 暂不支持发票

		List<Invoice> invoices = new ArrayList<Invoice>();

		Invoice invoice = new Invoice();

		/**
		 * 发票类型
		 * 
		 * */

		@NonNull
		int invoiceType = OrderParameterConstant.invoiceType;

		invoice.setInvoiceType(invoiceType);

		/**
		 * 发票抬头
		 * 
		 * */

		int invoiceTitle;

		/**
		 * 发票内容
		 * 
		 * */

		int invoiceContent;

		/**
		 * 发票金额
		 * 
		 * */

		int invoiceAmount;

		invoices.add(invoice);

		return invoices;
	}

	@Override
	public ApiResult<Boolean> syncItemSkuStock(Long itemId, Long skuId,
			Integer num, Boolean isAdd) {

		ApiResult<Boolean> apiRequest = itemSkuService.updateItemSkuNum(skuId,
				num, isAdd);

		return null;
	}
}
